package com.yu.controller;

import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;

import java.io.File;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.junit.runners.Parameterized.Parameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.annotation.JsonCreator.Mode;
import com.mysql.jdbc.StringUtils;
import com.sun.mail.handlers.image_gif;
import com.yu.bean.Msg;
import com.yu.bean.Picture;
import com.yu.bean.Tpicture;
import com.yu.dao.PictureMapper;
import com.yu.service.PictureService;
import com.yu.service.TpictureService;

@Controller
public class PictureController {
	
	@Autowired
	PictureService pictureService;
	
	@Autowired
	TpictureService tpictureService;
	
	@RequestMapping("/uploadLink")
	public String upLoadPage(){
		
		return "upload";
		
	}
	
	/**
	 * 获取已经存在的图片
	 * @param infoId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getPic/{infoId}", method=RequestMethod.GET)
	public Msg getPics(@PathVariable("infoId")String infoId){ //String前面不要有空格
		System.out.println("要获取的图片是"+infoId);
		Tpicture tpic = tpictureService.getTpicureById(infoId);
		List<Picture> cpics = pictureService.getPictureById(infoId);
		System.out.println("内容图片为"+cpics.size());
		if (tpic != null) {
			System.out.println("标题图片为"+tpic.getTpicUrl()+ "内容图片为"+cpics.size());
			return Msg.success().add("tpic", tpic).add("cpics", cpics) ;
		}else
			return Msg.success().add("cpics", cpics);
			
		
	}
	
	    /**
	     * @param files
	     * @param id
	     * @param request
	     * @return
	     * 上传图片
	     */
	    @ResponseBody
	    @RequestMapping(value="/uploadImg", method=RequestMethod.POST)
	    public Msg uploadPicture(
	    		@RequestParam(value="files",required=false)MultipartFile []files,
	            @RequestParam(value="id", required=false) String id,
	            HttpServletRequest request){
	    	//String selectedId = request.getParameter("selectedId");
	        File targetFile=null;
	        String storUrl="";//返回存储路径
	        List<Picture> pics = new ArrayList<>();
	        Picture pic = null;
	        System.out.println("开始上传图片呀呀呀呀呀呀"+files+"changdu"+files.length+"idweroe"+id);
	        if(files != null && files.length > 0 ){
	        	for(int i = 0; i < files.length; i++){
	        		String fileName=files[i].getOriginalFilename();//获取文件名加后缀 
		            String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/upload/imgs/";//存储路径
		            String path = request.getSession().getServletContext().getRealPath("upload/imgs"); //文件存储位置
		            String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
		            fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名
		            
		            //
		            File file1 =new File(path); 
		            System.out.println("图片的上传路径为："+path);
		            //如果文件夹不存在则创建    
		            if(!file1 .exists()  && !file1 .isDirectory()){       
		                file1 .mkdir();  
		            }
		            targetFile = new File(file1, fileName);
	                //targetFile = new File(path, fileName);
		            try {
		                files[i].transferTo(targetFile);
	                   //msg = returnUrl + fileName;
		               // msg=returnUrl+fileAdd+"/"+fileName;
		                storUrl=returnUrl+fileName;
		                System.out.println("图片的返回路径为"+storUrl);
		                pictureService.uploadImgs(id,storUrl);
		                pic = pictureService.selectPicByUrl(storUrl);
		                if (pic != null) {
		                	pics.add(pic);
						}
		            } catch (Exception e) {
		                e.printStackTrace();
		            }
		        }
	        }
	        System.out.println("shagnchuang成功了哎呀呀呀"+pics);
	        return Msg.success().add("pics", pics);
	}

    /**
     * 根据内容图片id 删除图片
     * @return
     */
	@ResponseBody 
	@RequestMapping(value="/delPic/{delId}", method=RequestMethod.DELETE)
    public Msg delPicById(@PathVariable("delId") String delId){
		Integer dId = Integer.parseInt(delId);
		pictureService.delPicById(dId);
		return Msg.success().add("msg", "删除图片数据成功！");
    	
    }
	
	
	/**
	 * 批量删除内容图片
	 * @param delIds
	 * @return
	 * jquery提交delete时，不支持@RequestParam，只支持@PathVariable形式
	 */
	@ResponseBody
	@RequestMapping(value="/delPics/{delIds}", method=RequestMethod.DELETE)
	public Msg delPicsById(@PathVariable("delIds")String delIds){
		System.out.println("要删除的数组是"+delIds);
		pictureService.delPicsById(delIds);
		return Msg.success().add("msg", "批量删除数据图片成功！");
		
	}
}